//
//  ScanViewController.swift
//  TestDemo
//
//  Created by 赵洋 on 2017/6/5.
//  Copyright © 2017年 赵洋. All rights reserved.
//

import UIKit
import AVFoundation
import MBProgressHUD


let scanRect = CGRect(x: screenWidth/2.0 - 140, y: screenHeight / 2.0 - 125, width: 280, height: 280)




class ScanViewController: UIViewController,AVCaptureMetadataOutputObjectsDelegate,UINavigationControllerDelegate {
    
    
    let  scanLine:UIImageView = {
        return UIImageView(image: UIImage(named: "qrcode_scan_light_green"))
    }()
    
    
    private let session:AVCaptureSession = {
        return AVCaptureSession()
    }()
    
    var borrow :Bool = true
    private var preViewLayer:AVCaptureVideoPreviewLayer!


    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        automaticallyAdjustsScrollViewInsets = true
        navigationController?.delegate = self
        view.backgroundColor = UIColor.white
        
        navigationController?.delegate = self 
        
        
        let authorizationStatus = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo)
        switch authorizationStatus {
        case .notDetermined:
            AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo, completionHandler: { [unowned self]grant in
                if grant {
                    self.setupSGQRCodeScanning()
                }
            })
        case .denied:
            let alertC = UIAlertController(title: "⚠️ 警告", message: "请去-> [设置 - 隐私 - 照片 - TestDemo] 打开访问开关", preferredStyle: .alert)
            let alertA = UIAlertAction(title: "确定", style: .default, handler: { [unowned self] action in
                self.navigationController?.popViewController(animated: true)
            })
            alertC.addAction(alertA)
            present(alertC, animated: true, completion: nil)
        case .restricted:
            let alertC = UIAlertController(title: "温馨提示", message: "由于系统原因, 无法访问相机", preferredStyle: .alert)
            let alertA = UIAlertAction(title: "确定", style: .default, handler: { [unowned self] action in
                self.navigationController?.popViewController(animated: true)
            })
            alertC.addAction(alertA)
            present(alertC, animated: true, completion: nil)
            
        case .authorized:
            setupSGQRCodeScanning()
        }
        
        
    }
    
    func setupSGQRCodeScanning()   {
        //1. 获取摄像设备
        let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)!
        //2. 创建输入流
        guard let deviceInput = try? AVCaptureDeviceInput(device: device)  else {
            MBProgressHUD.showErrorWith(text: "打开相机失败")
            
            return
        }
        //3.创建输出流
        let metadataOutput = AVCaptureMetadataOutput()
        //4.设置代理，在主线程里刷新
        metadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
        //设置扫描范围(每一个取值0~1 ，以屏幕的右上角为坐标原点)
        let scanScaleRect = CGRect(x: 1 - scanRect.maxX / screenWidth, y: scanRect.y / screenHeight, width: scanRect.width / screenWidth, height: scanRect.height / screenHeight)
        metadataOutput.rectOfInterest = scanScaleRect
        
        
        //5 初始化链接对象（会话对象）
        //let session = AVCaptureSession()
        //高质量的采集率
        session.canSetSessionPreset(AVCaptureSessionPresetHigh)
        //添加会话输入
        session.addInput(deviceInput)
        //添加会话输出
        session.addOutput(metadataOutput)
        //6.设置输出数据类型,需要将选数据输出添加到会话后，才能制定元数据类型，否则会报错
        //设置扫码支持的编码格式（如下设置条形码和二维码兼容）
        metadataOutput.metadataObjectTypes = [AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code,AVMetadataObjectTypeEAN8Code,AVMetadataObjectTypeCode128Code]
        
        //7.实例化预览图层，穿点session 是为了告诉图层捡来显示什么内容
        preViewLayer = AVCaptureVideoPreviewLayer(session: session)!
        preViewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
        preViewLayer.frame = self.view.bounds
        view.layer.insertSublayer(preViewLayer, at: 0)
        
        NotificationCenter.default.addObserver(forName: NSNotification.Name.AVCaptureInputPortFormatDescriptionDidChange, object: nil, queue: OperationQueue.current) {  [weak self] note  in
            if self != nil {
                metadataOutput.rectOfInterest = self!.preViewLayer.metadataOutputRectOfInterest(for:scanRect)
            }
        }
//
        //let scanView = QRScanView(ScanRect:scanRect)
        //view.addSubview(scanView)
        let scanView = UIImageView(image: UIImage(named: "Sao_sao"))
        scanView.frame = scanRect
        view.addSubview(scanView)
        scanLine.frame = CGRect(x: 10, y: 10, width: 260, height: 2)
        scanView.addSubview(scanLine)
        
        
        let _ = Timer.scheduledTimer(timeInterval: 4, target: self, selector: #selector(animate), userInfo: nil, repeats: true)

        
        session.startRunning()
    }
    
    func animate()  {
        UIView.animate(withDuration: 2, animations: {
        
            self.scanLine.transform = CGAffineTransform(translationX: 0, y: 240)
        }) { finished in
            UIView.animate(withDuration: 2, animations: { 
                self.scanLine.transform = CGAffineTransform.identity
            })
            
        }
    }
    
    
    //MARK:AVCaptureMetadataOutputObjectsDelegate
    func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) {
        //会频繁的扫码，调用代理方法
        
        //1.如果扫码完成，停止会话
        session.stopRunning()
        //2. 删除预览图层
        //preViewLayer.removeFromSuperlayer()
        //3.设置界面显示结果
        guard metadataObjects.count > 0 else {
            return
        }
        if let obj = metadataObjects.first as? AVMetadataMachineReadableCodeObject{
             print(obj.stringValue)
            let resultVC = ScanResultViewController()
            resultVC.scanResult = obj.stringValue
            navigationController?.pushViewController(resultVC, animated: true)
        }
    }
    
    //MARK:UINavigationControllerDelegate
    func navigationControllerSupportedInterfaceOrientations(_ navigationController: UINavigationController) -> UIInterfaceOrientationMask {

        return UIInterfaceOrientationMask.portrait

    }
    func navigationControllerPreferredInterfaceOrientationForPresentation(_ navigationController: UINavigationController) -> UIInterfaceOrientation {
        return .portrait
    }

}
